﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Autodesk.Revit.DB;
using YArchitech.LIB;
using YArchitech.Revit;

namespace System
{
	public static class Log
	{
		public static bool Enabled { get; set; }

		static Log()
		{
			Directory.CreateDirectory(Path.GetDirectoryName(Log.LogFile));
			Log.Enabled = false;
		}

		public static void Element(Element element)
		{
			if (element == null)
			{
				Log.Warning(new string[]
				{
					"Element is Null "
				});
				return;
			}
			Log.Info(new string[]
			{
				string.Format("Element Name = {0} , Mark={1}, Type =  {2}, Id = {3}", new object[]
				{
					element.Name,
					element.GetMark(),
					element.GetType(),
					element.Id.IntegerValue
				})
			});
		}

		public static void XYZ(XYZ point)
		{
			if (point == null)
			{
				Log.Warning(new string[]
				{
					"Point is Null "
				});
				return;
			}
			Log.Info(new string[]
			{
				string.Format("Point  = [{0} , {1},  {2}]", point.X, point.Y, point.Z)
			});
		}

		private static void WriteLog(IEnumerable<string> msgs)
		{
			if (!Log.Enabled)
			{
				return;
			}
			StreamWriter sw = File.Exists(Log.LogFile) ? File.AppendText(Log.LogFile) : File.CreateText(Log.LogFile);
			msgs.ForEach(delegate(string s)
			{
				sw.WriteLine(s);
			});
			sw.Close();
		}

		private static string FormatMessage(string msgType, string msg)
		{
			return string.Format("{0}\t{1}\t\t{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msgType, msg);
		}

		public static void Info(params string[] msgs)
		{
			Log.Info(msgs.AsEnumerable<string>());
		}

		public static void Info(IEnumerable<string> msgs)
		{
			Log.WriteLog(msgs.ForEach((string s) => Log.FormatMessage("Info", s)));
		}

		public static void Warning(params string[] msgs)
		{
			Log.Info(msgs.AsEnumerable<string>());
		}

		public static void Warning(IEnumerable<string> msgs)
		{
			Log.WriteLog(msgs.ForEach((string s) => Log.FormatMessage("Warning", s)));
		}

		public static void Error(params string[] msgs)
		{
			Log.Info(msgs.AsEnumerable<string>());
		}

		public static void Error(IEnumerable<string> msgs)
		{
			Log.WriteLog(msgs.ForEach((string s) => Log.FormatMessage("Error", s)));
		}

		private static readonly string WorkingLocation = string.IsNullOrEmpty(Product.WorkingLocation) ? Environment.ExpandEnvironmentVariables("%appdata%\\YArchitech\\HYRME2016") : Product.WorkingLocation;

		private static readonly string LogFile = Path.Combine(Log.WorkingLocation, string.Format("log\\{0}\\{1}.log", Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location), DateTime.Now.ToString("yyyy-MM-dd")));
	}
}
